import { createRouter, createWebHistory } from 'vue-router'
import { useAuthStore } from '@/stores/authStore'
import routers from './routers'
import { ElMessage } from 'element-plus'

let authStore = null

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: routers,
})

router.beforeEach(async (to, from, next) => {
  if (to.meta.isPublic) {
    next()
    return
  }
  if (authStore == null) {
    authStore = useAuthStore()
  }
  if (authStore.token == null) {
    ElMessage.error('请先登录')
    next({
      name: 'login',
    })
    return
  }
  if (authStore.menus.length == 0) {
    await authStore.initMenus()
  }

  if (to.path == '/home' || to.path == '/home/') {
    authStore.activeTitle = authStore.menus[0].right_name
    next({
      path: authStore.menus[0].right_path,
    })
    return
  }
  let flag = authStore.menus.some((item) => item.right_path == to.path)
  if (flag) {
    next()
  } else {
    next('/home/403')
  }
  // next()
})
export default router
